package com.richapp.launcher.service;

import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.richapp.launcher.R;
import com.richapp.launcher.busevent.EventServiceDestroy;
import com.richapp.launcher.database.system.dao.BoxModelDao;
import com.richapp.launcher.net.mobile.server.UserServer;
import com.richapp.launcher.net.remote.RemoteClient;
import com.richapp.launcher.serialport.infrared.InfraredServer;
import com.richapp.launcher.serialport.infrared.interfaces.IMessage;
import com.richapp.launcher.serialport.infrared.interfaces.InfraredMessageListener;
import com.richapp.launcher.serialport.infrared.message.ControlMessage;
import com.richapp.launcher.serialport.infrared.message.StudyMessage;
import com.richapp.net.util.HexTool;

import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * Created by jack on 2015/5/5 0005.
 */
public class InfraredService extends Service implements InfraredMessageListener {

    private static final String TAG = InfraredService.class.getName();

    private InfraredServer infraredServer = null;
    private BoxModelDao boxModelDao = null;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        infraredServer = InfraredServer.getInstance();
        infraredServer.setContext(this);
        infraredServer.setDeviceName(getResources().getString(R.string.infrared_device_name));
        infraredServer.setDeviceBit(getResources().getInteger(R.integer.infrared_device_bit));
        infraredServer.setDeviceFlag(getResources().getInteger(R.integer.infrared_device_flag));
        boxModelDao = new BoxModelDao(this);
        infraredServer.setInfraredMessageListener(this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                infraredServer.start();
            }
        }).start();
        //保持服务
        Notification notification = new Notification();
        startForeground(7, notification);
        //Toast.makeText(this, "红外服务启动", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        infraredServer.stop();
        EventBus.getDefault().post(new EventServiceDestroy(InfraredService.class));
    }

    /**
     * 红外消息接收处理
     * @param iMessage
     */
    @Override
    public void onInfraredMessage(IMessage iMessage) {
        try{
            if(iMessage instanceof ControlMessage){
                ControlMessage controlMessage = (ControlMessage)iMessage;
                byte[] result = controlMessage.getResult();
                int resultType = HexTool.HexToInt(HexTool.Byte2Hex(result[3]));
                String msg = "未定义红外反馈结果";
                String controlFlag = "false";
                switch (resultType){
                    case 0x01:
                        msg = "发送成功";
                        controlFlag = "true";
                        break;
                    case 0x02:
                        msg = "发送失败";
                        break;
                    case 0x03:
                        msg = "发送超时";
                        break;
                    default:
                        Log.e(TAG, "未定义红外反馈结果");
                }
                Log.d(TAG, msg);

                Map<String,Object> map = new HashMap<String,Object>();
                map.put("type",62);
                map.put("currentBoxCpuId",boxModelDao.getCurrentBox().getBoxCpuId());
                map.put("userName",controlMessage.getUserName());
                map.put("controlFlag",controlFlag);
                map.put("controlData",HexTool.ByteArrToHex(controlMessage.getControlData()));
                map.put("controlKey",controlMessage.getControlKey());

                msg = JSON.toJSONString(map);
                //发送用户数据
                UserServer.getInstance().sendAllUsersMessage(msg);
                //转发到服务器
                RemoteClient.getInstance().sendMessage(msg);

            }else if(iMessage instanceof StudyMessage){
                StudyMessage studyMessage = (StudyMessage)iMessage;
                byte[] result = studyMessage.getResult();
                String studyFlag = "false";

                Map<String,Object> map = new HashMap<String,Object>();
                map.put("type",57);
                map.put("currentBoxCpuId",boxModelDao.getCurrentBox().getBoxCpuId());
                map.put("userName",studyMessage.getUserName());
                map.put("studyKey",studyMessage.getStudyKey());

                String msg = "学习失败!";
                if(result != null){
                    studyFlag = "true";
                    msg = "恭喜,学习成功!";
                    ByteBuffer buffer = ByteBuffer.allocate(studyMessage.getDataBuffer().length -1);
                    buffer.put(studyMessage.getDataBuffer(),0,studyMessage.getDataBuffer().length-1);
                    map.put("controlData",HexTool.ByteArrToHex(buffer.array()));
                }else{

                }
                Log.d(TAG,msg);

                map.put("studyFlag",studyFlag);
                msg = JSON.toJSONString(map);
                //发送用户数据
                UserServer.getInstance().sendAllUsersMessage(msg);
                //转发到服务器
                RemoteClient.getInstance().sendMessage(msg);
            }else{
                Log.e(TAG,"未定义红外消息");
            }
        }catch (Exception e){
            Log.e(TAG,"红外消息接收错误:"+e.getMessage());
        }
    }
}
